﻿#include "Graphics.h"

#pragma comment(lib, "d3dx11.lib")
#pragma comment(lib, "d3d11.lib")

Graphics::Graphics(HWND hwnd)
{
    DXGI_SWAP_CHAIN_DESC sd = {};
    sd.BufferDesc.Width = 0;
    sd.BufferDesc.Height = 0;
    sd.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
    sd.BufferDesc.RefreshRate.Numerator = 0;
    sd.BufferDesc.RefreshRate.Denominator = 0;
    sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
    sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
    sd.SampleDesc.Count = 1;
    sd.SampleDesc.Quality = 0;
    sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    sd.BufferCount = 1;
    sd.OutputWindow = hwnd;
    sd.Windowed = TRUE;
    sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
    sd.Flags = 0;
    // 向返回函数传递了无效参数。 0x80070057
    HRESULT hresult = D3D11CreateDeviceAndSwapChain(
        nullptr,
        D3D_DRIVER_TYPE_HARDWARE,
        nullptr,
        0,
        nullptr,
        0,
        D3D11_SDK_VERSION,
        &sd,
        &this->_pSwap,
        &this->_pDevice,
        nullptr,
        &this->_pContext
        );
    if(hresult != 0)
    {
        // TODO log
        exit(DX_DEVICE_CREATE_ERROR_EXIT);
    }
}

Graphics::~Graphics()
{
    if(this->_pSwap != nullptr)
    {
        this->_pSwap->Release();
    }
    if(this->_pDevice != nullptr)
    {
        this->_pDevice->Release();
    }
    if(this->_pContext != nullptr)
    {
        this->_pContext->Release();
    }
}

void Graphics::EndFrame()
{
    // TODO 尝试绘图
    // this->_pDevice->ClearRenderTargetView()
    this->DrawTestTriangle();
    this->_pSwap->Present(1u, 0u);
}

void Graphics::DrawTestTriangle()
{
    // this->_pDevice->CreateBuffer();
    // this->_pDevice->BeginScene();
    //
    // this->_pDevice->Present(NULL, NULL, NULL, NULL);
    //
    // this->_pDevice->EndScene();
}
